<template>
  <div>
    <Search_top/>
    <div class="li_s">
      <p style="margin-bottom: 10px; margin-left: 10px; font-size: 16px;">
        历史搜索
        <span
          style="float: right; margin-right: 15px; font-size: 17px; color: gray;"
          @click="clearHistory"
        >
          <van-icon name="delete-o" />
        </span>
      </p>
      <ul v-if="searchHistory.length">
        <li v-for="(item, index) in searchHistory" :key="index" @click="selectHistory(item)">
          {{ item }}
        </li>
      </ul>
    </div>
    <div class="li_s">
      <p style="margin-bottom: 10px; margin-left: 10px; font-size: 16px;">热门搜索</p>
      <ul>
        <li v-for="(item, index) in hotRecommendList" :key="index">
          {{ item }} <van-icon name="fire" style="color: red;" />
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import Search_top from './Search_top.vue'

import axios from 'axios'
import { ref, onMounted } from 'vue'

import { useRouter } from 'vue-router'
const router = useRouter()
const value = ref('')


const hotRecommendList = [
  '阿胶',
  '沉香曲',
  '铁皮枫斗晶',
  '珍珠末',
  '蜂胶胶囊',
  '小金丸',
  '西洋参口服液'
]

// 读取本地存储的历史搜索记录
const searchHistory = ref<string[]>(JSON.parse(localStorage.getItem('searchHistory') || '[]'))
  const search = async () => {
  if (value.value.trim() === '') return;

  // 记录搜索历史
  addToSearchHistory(value.value);

  try {
    // 请求后端商品数据
    // console.log('value.value', value.value);
    
    const response = await axios.get(`http://localhost:3000/dyx/home?name=${value.value}`);
    // console.log(response);
    
    // 假设后端返回的数据是数组，处理返回数据
    if (response.data && response.data.data) {
      // 假设这里是搜索成功后的处理逻辑
      // 使用 router.push 跳转到搜索详情页，传递搜索名称
      router.push({ 
        path: '/search_result', 
        query: { name: value.value } // 将搜索名称传递为查询参数
      });
    } else {
      console.error('没有找到相关商品');
    }
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
}

// 添加搜索记录到历史
const addToSearchHistory = (item: string) => {
  if (!searchHistory.value.includes(item)) {
    searchHistory.value.push(item)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
}


// 选择历史搜索项
const selectHistory = (item: string) => {
  value.value = item
  search() // 可以直接进行搜索
}
// 清除历史搜索记录
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}




// 在组件挂载时读取历史记录
onMounted(() => {
  const history = JSON.parse(localStorage.getItem('searchHistory') || '[]')
  searchHistory.value = history
})
</script>

<style scoped>

.li_s {
  padding-top: 10px;
  width: 99%;
  margin: 0 auto;
}
.li_s ul {
  display: flex;
  flex-wrap: wrap;
}
.li_s ul li {
  background-color: rgba(247, 247, 247);
  padding: 5px 9px;
  border-radius: 50px;
  margin: 5px;
}
</style>
